import Card from '@/components/Card';
import Empty from '@/components/Empty';
import HealthReport from '@/components/HealthReport';
import AddMonthReport from '@/components/HealthReport/AddMonthReport';
import { ProForm, ProFormDatePicker, ProFormInstance } from '@/components/Pro/';
import { tempConsistControllerGetData as getData } from '@/services/ess/temperatureConsistencyAssessment';
import { QuestionCircleOutlined } from '@ant-design/icons';
import { useIntl } from '@umijs/max';
import { Badge, Flex, Pagination, Popover, Table, theme } from 'antd';
import cls from 'classnames';
import dayjs from 'dayjs';
import ReactEcharts from 'echarts-for-react';
import moment from 'moment';
import React, { useEffect, useRef, useState } from 'react';
import { useModel } from 'umi';
import Styles from './../index.less';

const { useToken } = theme;

const Index: React.FC = () => {
  const intl = useIntl();
  const isEnglish = intl.locale === 'en-US';
  const { token } = useToken();

  const formRef = useRef<ProFormInstance>();

  const { stationId } = useModel('@@initialState')?.initialState || {};

  const [pageData, setPageData] = useState<API.VoltageHealth>({});
  const [paginationConfig, setPaginationConfig] = useState({
    pageSize: 6,
    current: 1,
  });
  const [clusterList, setClusterList] = useState<API.ClusterHealth[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchTime, setSearchTime] = useState('');

  const submitForm = () => {
    formRef?.current?.submit();
  };

  useEffect(() => {
    submitForm();
  }, []);

  const chartData = [
    {
      value: pageData?.pie?.a || 0,
      name: intl.formatMessage({ id: 'batteryVoltage.vol.excellent' }),
      itemStyle: { color: token.colorExcellent },
    },
    {
      value: pageData?.pie?.b || 0,
      name: intl.formatMessage({ id: 'batteryVoltage.vol.good' }),
      itemStyle: { color: token.colorGood },
    },
    {
      value: pageData?.pie?.c || 0,
      name: intl.formatMessage({ id: 'batteryVoltage.vol.average' }),
      itemStyle: { color: token.colorAverage },
    },
    {
      value: pageData?.pie?.d || 0,
      name: intl.formatMessage({ id: 'batteryVoltage.vol.poor' }),
      itemStyle: { color: token.colorPoor },
    },
    {
      value: pageData?.pie?.f || 0,
      name: intl.formatMessage({ id: 'batteryVoltage.vol.other' }),
      itemStyle: { color: token.colorOther },
    },
  ];

  const findMax = () => {
    let text = [];
    const { a, b, c, d, f } = pageData?.pie || {};
    const max = Math.max(a, b, c, d, f);
    if (a === max) {
      text.push(intl.formatMessage({ id: 'batteryVoltage.vol.excellent' }));
    }
    if (b === max) {
      text.push(intl.formatMessage({ id: 'batteryVoltage.vol.good' }));
    }
    if (c === max) {
      text.push(intl.formatMessage({ id: 'batteryVoltage.vol.average' }));
    }
    if (d === max) {
      text.push(intl.formatMessage({ id: 'batteryVoltage.vol.poor' }));
    }
    if (f === max) {
      text.push(intl.formatMessage({ id: 'batteryVoltage.vol.other' }));
    }
    return text.join(' ');
  };

  const date: string =
    formRef?.current?.getFieldFormatValue()?.date ||
    moment().subtract(1, 'day').format('YYYY-MM-DD');

  return (
    <>
      <Card bodyStyle={{ paddingTop: 15, paddingBottom: 15 }}>
        <Flex justify="space-between" align="center">
          <ProForm
            layout="inline"
            formRef={formRef}
            onFinish={async (value) => {
              setSearchTime(value.date + ' ' + moment().format('HH:mm:ss'));
              try {
                setLoading(true);
                const reslut = await getData({
                  ...value,
                  stationId,
                });
                setLoading(false);
                if (reslut.success) {
                  const data = reslut?.data || {};
                  setPageData(data);
                  let tempClusterList: API.ClusterHealth[] = [];
                  (data.boxList || []).forEach((item: API.BoxHealth) => {
                    tempClusterList = [...tempClusterList, ...(item.clusterList || [])];
                  });
                  setClusterList(tempClusterList);
                } else {
                  setPageData({});
                  setClusterList([]);
                }
              } catch (e) {
                setPageData({});
                setClusterList([]);
              }
            }}
            submitter={{
              searchConfig: {
                submitText: intl.formatMessage({ id: 'batteryVoltage.vol.search' }),
              },
              resetButtonProps: false,
            }}
          >
            <ProFormDatePicker
              width={260}
              name="date"
              label={intl.formatMessage({ id: 'batteryVoltage.vol.voltageDate' })}
              initialValue={moment().subtract(1, 'day')}
              fieldProps={{
                disabledDate: (current) => {
                  return current && current >= dayjs().endOf('day');
                },
                allowClear: false,
              }}
            />
          </ProForm>
          <HealthReport date={searchTime} />
        </Flex>
      </Card>
      <Card
        loading={loading}
        title={
          <span>
            {intl.formatMessage({ id: 'batteryVoltage.vol.distributionMap' })}
            <span className={Styles.totalNumber}>
              {intl.formatMessage({ id: 'batteryVoltage.vol.boxTotalNum' })}
              {pageData.boxCount}
            </span>
            <span className={Styles.totalNumber}>
              {intl.formatMessage({ id: 'batteryVoltage.vol.clusterTotalNum' })}
              {pageData.clusterCount}
            </span>
          </span>
        }
        extra={
          <div>
            <AddMonthReport date={date} />
            <Popover
              placement="bottomRight"
              title={false}
              content={
                <div className={Styles.standardDesc}>
                  <ul>
                    <li key="1">1.{intl.formatMessage({ id: 'batteryVoltage.tips.one' })}</li>
                    <li key="2">
                      2. {intl.formatMessage({ id: 'batteryVoltage.tips.two' })}
                      <p>|- A+A=&gt;A+</p>
                      <p>|- A+B=&gt;A-&nbsp;&nbsp;&nbsp;B+B=&gt;B+</p>
                      <p>
                        |-
                        A+C=&gt;B&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;B+C=&gt;B-&nbsp;&nbsp;&nbsp;C+C=&gt;C+
                      </p>
                      <p>
                        |-
                        A+D=&gt;C+&nbsp;&nbsp;&nbsp;B+D=&gt;C&nbsp;&nbsp;&nbsp;C+D=&gt;C-&nbsp;&nbsp;&nbsp;D+D=&gt;D
                      </p>
                    </li>
                    <li key="3">
                      3.
                      {intl.formatMessage({ id: 'batteryVoltage.tips.three' })}
                    </li>
                  </ul>
                  <div>{intl.formatMessage({ id: 'batteryVoltage.tips.four' })}</div>
                  <Flex justify="space-between">
                    <table>
                      <tbody>
                        <tr>
                          <td>{intl.formatMessage({ id: 'batteryVoltage.tips.five' })}</td>
                          <td>{intl.formatMessage({ id: 'batteryVoltage.tips.six' })}</td>
                        </tr>
                        <tr>
                          <td>[0，8)</td>
                          <td>A</td>
                        </tr>
                        <tr>
                          <td>[8，10)</td>
                          <td>B</td>
                        </tr>
                        <tr>
                          <td>[10，12)</td>
                          <td>C</td>
                        </tr>
                        <tr>
                          <td>[12，+∞)</td>
                          <td>D</td>
                        </tr>
                      </tbody>
                    </table>
                    <table>
                      <tbody>
                        <tr>
                          <td>{intl.formatMessage({ id: 'batteryVoltage.tips.seven' })}</td>
                          <td>{intl.formatMessage({ id: 'batteryVoltage.tips.six' })}</td>
                        </tr>
                        <tr>
                          <td>[0，0.06)</td>
                          <td>A</td>
                        </tr>
                        <tr>
                          <td>[0.06，0.08)</td>
                          <td>B</td>
                        </tr>
                        <tr>
                          <td>[0.08，0.1)</td>
                          <td>C</td>
                        </tr>
                        <tr>
                          <td>[0.1，+∞)</td>
                          <td>D</td>
                        </tr>
                      </tbody>
                    </table>
                  </Flex>
                </div>
              }
              arrow={true}
            >
              <a href="#">
                <QuestionCircleOutlined className={Styles.btnIcon} />
                &nbsp;{intl.formatMessage({ id: 'batteryVoltage.vol.standard' })}
              </a>
            </Popover>
          </div>
        }
        style={{ marginTop: 20, minHeight: 200 }}
        hasHeaderBorder={true}
      >
        <div className={Styles.batteryContainer}>
          <Flex gap={24} wrap="wrap">
            {pageData.boxList?.length ? (
              pageData.boxList.map((item, index) => (
                <div className={Styles.batteryItem} key={index}>
                  <Flex justify="space-between">
                    <h5 className={Styles.title}>
                      {item.name}/{intl.formatMessage({ id: 'batteryVoltage.vol.clusterNum' })}
                      {item.clusterCount}
                    </h5>
                    <div className={Styles.summary}>
                      <Badge
                        count={intl.formatMessage({ id: 'batteryVoltage.vol.excellent' })}
                        color={token.colorExcellent}
                      />
                      <span className={Styles.num}>
                        {item.a}
                        {intl.formatMessage({ id: 'batteryVoltage.safe.indivual' })}
                      </span>
                      <Badge
                        count={intl.formatMessage({ id: 'batteryVoltage.vol.good' })}
                        color={token.colorGood}
                      />
                      <span className={Styles.num}>
                        {item.b}
                        {intl.formatMessage({ id: 'batteryVoltage.safe.indivual' })}
                      </span>
                      <Badge
                        count={intl.formatMessage({ id: 'batteryVoltage.vol.average' })}
                        color={token.colorAverage}
                      />
                      <span className={Styles.num}>
                        {item.c}
                        {intl.formatMessage({ id: 'batteryVoltage.safe.indivual' })}
                      </span>
                      <Badge
                        count={intl.formatMessage({ id: 'batteryVoltage.vol.poor' })}
                        color={token.colorPoor}
                      />
                      <span className={Styles.num}>
                        {item.d}
                        {intl.formatMessage({ id: 'batteryVoltage.safe.indivual' })}
                      </span>
                    </div>
                  </Flex>
                  <Flex className={`${Styles.contentBox} ${isEnglish ? Styles.contentBoxEn : ''}`}>
                    {(item.clusterList || []).map((clusterItem, _index) => (
                      <Popover
                        placement="top"
                        title={false}
                        key={_index}
                        content={
                          <div style={{ marginTop: 10 }}>
                            <ul>
                              <li>
                                {intl.formatMessage({ id: 'batteryVoltage.vol.clusterName' })} :{' '}
                                {clusterItem.name}
                              </li>
                              <li>
                                {intl.formatMessage({
                                  id: 'batteryVoltage.vol.comprehensiveScore',
                                })}{' '}
                                : {clusterItem.score}
                                {intl.formatMessage({
                                  id: 'batteryVoltage.vol.score',
                                })}
                              </li>
                              <li>
                                {intl.formatMessage({ id: 'batteryVoltage.no' })} :{' '}
                                {clusterItem.code}
                              </li>
                              <li>ID : {clusterItem.clusterId}</li>
                              <li>
                                {intl.formatMessage({ id: 'batteryVoltage.vol.chargeLevel' })} :{' '}
                                {clusterItem.chargeLevel}
                              </li>
                              <li>
                                {intl.formatMessage({ id: 'batteryVoltage.vol.dischargeLevel' })} :{' '}
                                {clusterItem.dischargeLevel}
                              </li>
                              <li>
                                {intl.formatMessage({
                                  id: 'batteryVoltage.vol.comprehensiveLevel',
                                })}{' '}
                                : {clusterItem.comprehensiveLevel}
                              </li>
                              <li>
                                {intl.formatMessage({ id: 'batteryVoltage.vol.uniformity' })} :{' '}
                                {clusterItem.consistency}
                              </li>
                            </ul>
                          </div>
                        }
                      >
                        <dl
                          className={cls({
                            [Styles.crowd]: true,
                            [Styles.excellent]:
                              clusterItem.consistency ===
                              intl.formatMessage({ id: 'batteryVoltage.vol.excellent' }),
                            [Styles.good]:
                              clusterItem.consistency ===
                              intl.formatMessage({ id: 'batteryVoltage.vol.good' }),
                            [Styles.average]:
                              clusterItem.consistency ===
                              intl.formatMessage({ id: 'batteryVoltage.vol.average' }),
                            [Styles.poor]:
                              clusterItem.consistency ===
                              intl.formatMessage({ id: 'batteryVoltage.vol.poor' }),
                          })}
                          key={_index}
                        >
                          <dt>{clusterItem.shortName}</dt>
                          <dd>
                            <Flex justify="space-between">
                              <span>
                                {intl.formatMessage({ id: 'batteryVoltage.vol.chargeLevel' })}
                              </span>
                              <span>{clusterItem.chargeLevel}</span>
                            </Flex>
                            <Flex justify="space-between">
                              <span>
                                {intl.formatMessage({ id: 'batteryVoltage.vol.dischargeLevel' })}
                              </span>
                              <span>{clusterItem.dischargeLevel}</span>
                            </Flex>
                            <Flex justify="space-between">
                              <span>
                                {intl.formatMessage({
                                  id: 'batteryVoltage.vol.comprehensiveLevel',
                                })}
                              </span>
                              <span>{clusterItem.comprehensiveLevel}</span>
                            </Flex>
                            <Flex justify="space-between" wrap="wrap">
                              <span>
                                {intl.formatMessage({ id: 'batteryVoltage.vol.uniformity' })}
                              </span>
                              <span>{clusterItem.consistency}</span>
                            </Flex>
                          </dd>
                        </dl>
                      </Popover>
                    ))}
                  </Flex>
                </div>
              ))
            ) : (
              <Empty style={{ height: 220 }} />
            )}
          </Flex>
        </div>
      </Card>
      <Flex style={{ marginTop: 20 }}>
        <Card
          title={intl.formatMessage({ id: 'batteryVoltage.vol.overall' })}
          style={{ width: '40%', marginRight: 20, minWidth: 560 }}
          bodyStyle={{ paddingBottom: 0 }}
          loading={loading}
        >
          {typeof pageData?.pie?.total === 'number' && pageData?.pie?.total > 0 ? (
            <ReactEcharts
              option={{
                title: [
                  {
                    text: findMax(),
                    top: '41%', // 控制位置
                    left: '31%', // 控制位置
                    textAlign: 'center', // 让文字居中
                    textStyle: {
                      fontSize: 24,
                      color: token.colorText,
                    },
                  },
                  {
                    text: intl.formatMessage({ id: 'batteryVoltage.vol.highest' }),
                    top: '51%', // 控制位置
                    left: '31%', // 控制位置
                    textAlign: 'center', // 让文字居中
                    textStyle: {
                      fontSize: 14,
                      color: token.colorText,
                    },
                  },
                  {
                    text: `${intl.formatMessage({ id: 'batteryVoltage.sum' })}  ${
                      pageData?.pie?.total || 0
                    }${intl.formatMessage({ id: 'batteryVoltage.cluster' })}`,
                    top: '18%', // 控制位置
                    left: '70%', // 控制位置
                    textStyle: {
                      fontSize: 16,
                      color: token.colorText,
                      bold: 'normal',
                    },
                  },
                ],
                tooltip: {
                  trigger: 'item', // 触发机制，鼠标悬浮圆环项上
                  show: true, // 控制鼠标悬浮是否显示数据
                },
                legend: {
                  orient: 'vertical', // 控制水平排列
                  top: '32%', // 调整位置
                  right: '2%', // 距离右侧位置
                  icon: 'circle', // 修改小图标为圆形
                  itemHeight: 12, // 修改圆形小图标的大小
                  textStyle: {
                    // 文字的样式
                    fontSize: 24, // 可控制每个legend项的间距
                    color: token.colorText,
                    rich: {
                      // 通过富文本rich给每个项设置样式，下面的oneone、twotwo、threethree可以理解为"每一列"的样式
                      oneone: {
                        // 设置文字、数学、英语这一列的样式
                        width: 48,
                        fontSize: 12,
                        fontWeight: 'bolder',
                      },
                      twotwo: {
                        // 设置10分、20分、30分这一列的样式
                        width: 65,
                        fontSize: 12,
                      },
                      threethree: {
                        // 设置百分比这一列的样式
                        width: 60,
                        fontSize: 12,
                      },
                    },
                  },
                  formatter: (name: string) => {
                    const total = pageData?.pie?.total as number;
                    const target = chartData.find((item) => item.name === name)?.value ?? 0;
                    let v = ((target / total) * 100).toFixed(2);

                    return `{oneone|${name}} {twotwo|${v}%} {threethree|${target} ${intl.formatMessage(
                      { id: 'batteryVoltage.cluster' },
                    )}}`;
                    //     富文本第一列样式应用    富文本第二列样式应用      富文本第三列样式应用
                  },
                },
                series: [
                  {
                    data: chartData,
                    name: intl.formatMessage({ id: 'batteryVoltage.vol.uniformity' }),
                    type: 'pie', // 类型为饼图
                    radius: ['40%', '65%'], // 圆环分为内径和外径，就是两个半径不一样的饼图可组成一个圆环图，radius数组中的两项分别为内径和外径（相对画布的百分比）
                    center: ['32%', '50%'], // 调整圆环图位置
                    avoidLabelOverlap: true, // 防止牵引线堆叠挤在一块
                    label: {
                      normal: {
                        show: true,
                        position: 'outside', // 另有参数inside，可以让数据在圆环上
                        formatter: '{d}%', //模板变量有 {a}、{b}、{c}、{d}，分别表示系列名，数据名，数据值，百分比。{d}数据会根据value值计算百分比
                        textStyle: {
                          // 牵引线上的文字的样式
                          align: 'right',
                          baseline: 'middle',
                          fontFamily: '微软雅黑',
                          fontSize: 12,
                          fontWeight: 'bolder',
                          color: '#333',
                        },
                      },
                    },
                    labelLine: {
                      show: true, // 是否显示延展线
                      length: 10, // 延展线条的长度
                    },
                  },
                ],
              }}
            />
          ) : (
            <div style={{ position: 'relative', marginTop: -15 }}>
              <ReactEcharts
                style={{
                  height: 280,
                }}
                option={{
                  title: [
                    {
                      text: '--',
                      top: '41%', // 控制位置
                      left: '26%', // 控制位置
                      textAlign: 'center', // 让文字居中
                      textStyle: {
                        fontSize: 24,
                        color: token.colorText,
                      },
                    },
                    {
                      text: intl.formatMessage({ id: 'batteryVoltage.vol.highest' }),
                      top: '51%', // 控制位置
                      left: '26%', // 控制位置
                      textAlign: 'center', // 让文字居中
                      textStyle: {
                        fontSize: 14,
                        color: token.colorText,
                      },
                    },
                  ],
                  series: [
                    {
                      data: [{ value: 100, name: '', itemStyle: { color: '#F0F1F5' } }],
                      name: 'Access From',
                      type: 'pie',
                      radius: ['47%', '70%'],
                      center: ['27%', '50%'],
                      avoidLabelOverlap: false,
                      label: {
                        show: false,
                        position: 'center',
                      },
                      emphasis: {
                        label: {
                          show: true,
                          fontSize: 40,
                          fontWeight: 'bold',
                        },
                      },
                      labelLine: {
                        show: false,
                      },
                    },
                  ],
                }}
              />
              <div className={Styles.chartEmpty}>
                <div className={Styles.total}>
                  {intl.formatMessage({ id: 'batteryVoltage.sum' })}--
                  <span className={Styles.unit}>
                    {' '}
                    {intl.formatMessage({ id: 'batteryVoltage.cluster' })}
                  </span>
                </div>
                <ul>
                  {chartData.map((item) => (
                    <li key={item.name}>
                      <span
                        className={Styles.icon}
                        style={{ backgroundColor: item.itemStyle.color }}
                      ></span>
                      <span>{item.name}</span>
                      <span>--%</span>
                      <span>--{intl.formatMessage({ id: 'batteryVoltage.cluster' })}</span>
                    </li>
                  ))}
                </ul>
              </div>
            </div>
          )}
        </Card>
        <Card
          title={intl.formatMessage({ id: 'batteryVoltage.vol.details' })}
          style={{ flex: 1 }}
          bodyStyle={{ paddingBottom: 0 }}
          loading={loading}
        >
          <Table
            className="table-split-line"
            columns={[
              {
                title: intl.formatMessage({ id: 'batteryVoltage.tableNo' }),
                dataIndex: 'pageIndex',
                render: (_, record, index) =>
                  (paginationConfig.current - 1) * paginationConfig.pageSize + index + 1,
              },
              {
                title: intl.formatMessage({ id: 'batteryVoltage.vol.clusterCode' }),
                dataIndex: 'name',
                sorter: (a, b) => a.code - b.code,
              },
              {
                title: intl.formatMessage({ id: 'batteryVoltage.vol.chargeLevel' }),
                dataIndex: 'chargeLevel',
                sorter: (a, b) => a.chargeLevelScore - b.chargeLevelScore,
              },
              {
                title: intl.formatMessage({ id: 'batteryVoltage.vol.dischargeLevel' }),
                dataIndex: 'dischargeLevel',
                sorter: (a, b) => a.dischargeLevelScore - b.dischargeLevelScore,
              },
              {
                title: intl.formatMessage({ id: 'batteryVoltage.vol.comprehensiveLevel' }),
                dataIndex: 'comprehensiveLevel',
                sorter: (a, b) => a.score - b.score,
              },
              {
                title: intl.formatMessage({ id: 'batteryVoltage.vol.uniformity' }),
                dataIndex: 'consistency',
                sorter: (a, b) => a.score - b.score,
              },
            ]}
            dataSource={clusterList}
            size="small"
            rowKey="code"
            pagination={{
              pageSize: paginationConfig.pageSize,
              pageSizeOptions: [6, 10, 20, 50, 100],
              onChange: (page, pageSize) => {
                setPaginationConfig({
                  current: page,
                  pageSize: pageSize,
                });
              },
            }}
          />
          {!clusterList?.length && (
            <Flex justify="right" style={{ margin: '16px 0' }}>
              <Pagination
                size="small"
                total={0}
                showSizeChanger
                showQuickJumper
                defaultPageSize={20}
              />
            </Flex>
          )}
        </Card>
      </Flex>
    </>
  );
};

export default Index;
